<?php
/**
 * show file icon for download and preview
 * @param $link/$sql to direct to that file
 * @return unknown_type
 *
 *
	$param = array(
		'file_path' => $file_path,//full path and file name
		'file_name' => $k.'.'.$type,
		'info' => $files[$k]['description'],
		'file_type' => $type,
		'show_act' => 1,// for show word [download, preview] after icon
	);

	fw_file_show($param,$show_type='download')
	#'dbcon_invoice' => 'dbcon_invoice', // for get content from other database
	#'file_query' => 'SELECT file_blob FROM table WHERE id=1', //for get file from database
 */
function fw_file_show($param, $show_type = 'download'){ //show_type=preview
	global $db, $config;
	$type_preview = array('png', 'bmp', 'gif', 'jpg', 'jpeg', 'pdf');
	if (isset($param['file_query'])) {
		#set param ['file_path']
		if (!isset($param['file_name'])) {
			//return 'set: $param[file_name]';
			$param['file_name'] = $_SESSION[SESSION_L].time();
		}
		if (!isset($param['file_type'])) {
			return 'set: $param[file_type]';
		}
		if (!isset($param['file_path'])) {
			#set file path
			$param['file_path'] = "files/temp/".$param['file_name'];
		}
	}

	$add_link = '&file_type='.$param['file_type'].'&file_name='.$param['file_name'].'&file_path='.$param['file_path'];
	if (isset($param['file_query'])) {
		$add_link .= '&field='.$param['file_query']['field'];
		$add_link .= '&table='.$param['file_query']['table'];
		if ($param['file_query']['where']) {
			foreach ($param['file_query']['where'] as $f => $v) {
				$add_link .= '&where['.$f.']='.$v;
			}
		}
	}

	if (isset($param['dbcon'])) {
		$add_link .= '&dbcon='.$param['dbcon'];
	}

	$add_link .= '&fajax=1';
	if (isset($param['file_path'])) {
		$target_path = $param['file_path'];
		//dont add span
		$param['title'] = 0;
		if ($show_type == 'download') {
			$param['info'] = msg('download').': '.$param['file_name'];
			if ($param['show_act'] == 1) {
				$show_act = ' '.msg('download');
			}
			$r = ' <a href="index.php?mod=file&view=download'.$add_link.'"><img src="im/file_download.png" title="'.$param['info'].'"/>'.$show_act.'</a>';
		} else {#preview
			$param['info'] = msg('preview').': '.$param['file_name'];
			if ($param['show_act'] == 1) {
				$show_act = ' '.msg('preview');
			}
			if (in_array($param['file_type'], $type_preview)) {
				if ($param['file_type'] == 'pdf') {
					$r = ' <a onclick="show_popup_link(this,\'mod=file&view=preview'.$add_link.'\',0,\'auto\');" href="#preview"><img src="im/file_preview.png" title="'.$param['info'].'"/>'.$show_act.'</a>';
				} else {
					$path_img = str_replace('index.php', '', $_SERVER['PHP_SELF']);
					$r = ' <a class="fancybox" title="'.$param['info'].'" href="'.$path_img.$target_path.'"><img src="im/file_preview.png" title="'.$param['info'].'"/>'.$show_act.'</a>';
				}
			}
		}
	} else {
		$r = 'set: $param[file_path]';
	}
	return $r;
}

//
function fw_file_preview3(){
	//create file to tmp folder and call function fw_file_show for display it
	$entity = $_REQUEST['entity'];
	$date = $_REQUEST['date'];
	$id = $_REQUEST['id'];
	$key = $_REQUEST['key'];
	$file_name = $_REQUEST['file_name'];
	$ext = $_REQUEST['type'];

	//get file details
	//TODO beem
//	$ext = fw_file_extension($file_name);
//	$name = fw_file_name($file_name);
	$name = $file_name;
	$file_info = fw_file_details($entity, $date, $id, $key, $name, $ext);
	$dir_tmp = 'files/temp/';

	if ($_REQUEST['path'] == 1) {
		$dir = 'files/'.$entity.'/';
	} else {
		$dir = 'files/data/';
	}

	$original = $dir . $file_info['file_path'];
	$file_name_download = $file_info['file_name_download'];

	$new_file = $dir_tmp . $name . '.'. $ext;
	//copy file
//	$ext = fw_file_extension($file_name);
	if ($ext == 'pdf') {
		if (copy($original, $new_file)) {
			if ($ext == 'pdf') {
				echo '<div class="popupHeader">'.msg('preview').': '.$file_name_download.'</div>';
				$file_swf = 'files/temp/'.str_replace('.pdf','.swf', $_SESSION[SESSION_L].time().'-'.$file_name_download);
				system('PATH=/usr/local/bin/ pdf2swf -B lib/pdf2swf/rfxview.swf '.$new_file.' -o '.$file_swf.'> /dev/null 2>&1');
				if (!file_exists($file_swf)) {
					system('PATH=/usr/local/bin/ pdf2swf -B lib/pdf2swf/rfxview.swf -s poly2bitmap '.$new_file.' -o '.$file_swf.'> /dev/null 2>&1');
				}
				//echo $file_swf;
				if (file_exists($file_swf)) {
				$r = '
				  <div id="file_preview"></div>
				  <script type="text/javascript">
				  	$(document).ready(function(){
						$("#file_preview").flash({
							src: "'.$file_swf.'",
							width: 700,
							height: 400,
							flashvars: { zoomtype: "1"}
						});
					});
				  </script>';
				} else {
					$r = 'Cannot preview';
				}
				echo $r;
			}
		}
	} else {
		$add_link = '&entity=' . $entity . '&date=' . $date . '&id=' . $id . '&key=' . $key . '&file_name=' . $file_name . '&type=' . $ext . '&fajax=1';
		//download
		$link = 'index.php?mod=file&view=download3&path=1' . $add_link;
		$size = GetImageSize($original);
		echo '<img style="width: '.$size[0].'px;height: '.$size[1].'px;" src="' . $link.'"/>';
		exit;
	}
}

function fw_file_create(){
	global $db, $config;
	if ($_REQUEST['table']) {
		if ($_REQUEST['where']) {
			$k = 0;
			foreach ($_REQUEST['where'] as $f => $v) {
				if (++$k>1) {
					$where .= ' AND ';
				}
				$where .= $f.'="'.$v.'"';
			}
		}
		$sql = 'SELECT '.$_REQUEST['field'].' FROM '.$_REQUEST['table'].' WHERE '.$where;
		#get file content
		if (isset($_REQUEST['dbcon'])) {
			$db2 = ADONewConnection($config[$_REQUEST['dbcon']]);
			$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
			$file_content = $db2->GetOne($sql);
			file_put_contents($_REQUEST['file_path'],$file_content);
		} else {
			$file_content = $db->GetOne($sql);
			file_put_contents($_REQUEST['file_path'],base64_decode($file_content));
		}
	}
}

function fw_file_preview(){
	global $db;
	$file_path = $_REQUEST['file_path'];
	$type = $_REQUEST['file_type'];
	#create file in temp
	fw_file_create();

	if ($type == 'pdf') {
		echo '<div class="popupHeader">'.msg('preview').': '.$_REQUEST['file_name'].'</div>';
		$file_swf = 'files/temp/'.str_replace('.pdf','.swf', $_SESSION[SESSION_L].time().'-'.$_REQUEST['file_name']);
		//echo 'PATH=/usr/local/bin/ pdf2swf -B lib/pdf2swf/rfxview.swf '.$file_path.' -o '.$file_swf.'> /dev/null 2>&1';
		system('PATH=/usr/local/bin/ pdf2swf -B lib/pdf2swf/rfxview.swf '.$file_path.' -o '.$file_swf.'> /dev/null 2>&1');
		if (!file_exists($file_swf)) {
			system('PATH=/usr/local/bin/ pdf2swf -B lib/pdf2swf/rfxview.swf -s poly2bitmap '.$file_path.' -o '.$file_swf.'> /dev/null 2>&1');
		}
		//echo $file_swf;
		if (file_exists($file_swf)) {
		$r = '
		  <div id="file_preview"></div>
		  <script type="text/javascript">
		  	$(document).ready(function(){
				$("#file_preview").flash({
					src: "'.$file_swf.'",
					width: 700,
					height: 400,
					flashvars: { zoomtype: "1"}
				});
			});
		  </script>';
		} else {
			$r = 'Cannot preview';
		}
		echo $r;
	}else if ($type == 'jpg' || $type == 'png' || $type == 'jpeg' || $type == 'gif' || $type == 'bmp') { #TODO use lib
		if (file_exists($file_path)) {
			echo '<a class="fancybox" title="'.gain_plug_cut($param).'" href="'.PATH.$file_path.'">
			<img alt="'.gain_plug_cut($param).'" src="lib/class/image.php?width=100&height=100&cropratio=1:1&image=/'.$file_path.'"/>
			</a>';
		} else {
			echo $file_path;
		}
	}
}

function fw_file_download2(){
	global $db, $gv, $global_config;

	$file_path = $_REQUEST['file_path'];
	$type = $_REQUEST['file_type'];
	$file_name = $_REQUEST['file_name'];
	//$original = $file_path
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Cache-Control: private", false);
	header('Content-type: '.$global_config['system']['ext_allow'][$type]);
	header('Content-Disposition: attachment; filename="'.$file_name.'"');
	header("Content-Transfer-Encoding: binary");
	header("Content-Length: ".filesize($file_path));
	readfile($file_path);
	exit;
}

function fw_file_download3(){
	global $global_config;

	$entity = $_REQUEST['entity'];
	$date = $_REQUEST['date'];
	$id = $_REQUEST['id'];
	$key = $_REQUEST['key'];
	$file_name = $_REQUEST['file_name'];
	$type = $_REQUEST['type'];

	$file_info = fw_file_details($entity, $date, $id, $key, $file_name, $type);

	if ($_REQUEST['path'] == 1) {
		$dir = 'files/'.$entity.'/';
	} else {
		$dir = 'files/data/';
	}

	$file_path = $dir . $file_info['file_path'];
	$file_name_download = $file_info['file_name_download'];
	//$original = $file_path
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Cache-Control: private", false);
	header('Content-type: '.$global_config['system']['ext_allow'][$type]);
	header('Content-Disposition: attachment; filename="'.$file_name_download.'"');
	header("Content-Transfer-Encoding: binary");
	header("Content-Length: ".filesize($file_path));
	readfile($file_path);
	exit;
}

function fw_file_details($entity, $date, $id, $key, $file_name, $type){
	global $global_config;
	//set global config for allow extenstion
	//$allow_extention = array_keys($global_config['system']['ext_allow']);
	$dir = date('Y', strtotime($date)).'/'.date('m', strtotime($date)).'/';

	//$type = fw_file_extension($file_name);
	//$orginal_file = fw_file_name($file_name);

	//create original path here
	$file_path = $dir . $entity . '_' . $id . '_'. $key . '_' . $file_name ;

	$file_name_download = $entity . '_' . $id . '.' . $type;
	return array('dir_tmp' => $dir . 'tmp/', 'file_path' => $file_path, 'file_name_download' => $file_name_download);
}

function fw_file_download(){
	global $db, $gv;
	$file_path = $_REQUEST['file_path'];
	$type = $_REQUEST['file_type'];
	#create file in temp
	fw_file_create();

	header('Pragma: public');
	header('Expires: 0');
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	header('Cache-Control: public');
	header('Content-Description: File Transfer');
	header('Content-Type: application/force-download');
	header('Content-Disposition: attachment; filename='.urlencode($_REQUEST['file_name']));
	header('Content-Transfer-Encoding: binary');
	readfile($file_path);
	exit();
}

function fw_file_extension($name){
	if ($name) {
		$file = explode('.', $name);
  		return strtolower($file[count($file)-1]);
	} else {
		return false;
	}
}

function fw_file_name($name){
  	return substr($name, 0, strrpos($name, '.'));
}

function fw_file_move($s_dir,$source,$d_dir,$destination){
	$s_dir = fw_clean_dir_path($s_dir);
	$d_dir = fw_clean_dir_path($d_dir);

	if (!strstr($s_dir, PATH)) {
		$s_dir = PATH.$s_dir;
	}
	if (!strstr($d_dir, PATH)) {
		$d_dir = PATH.$d_dir;
	}
	if (!is_dir($d_dir)) {
		fw_mkdir($d_dir);
	}

	$r = rename($s_dir.$source, $d_dir.$destination);
	if (FILE_CHMOD != '') {
		$r = chmod($d_dir.$destination, FILE_CHMOD);
	}
	return $r;
}

function fw_clean_dir_path($dir){
	//cleanup folder name
	if (substr($dir, 0, 1) == '/') {
		$dir = substr($dir,1);
	}
	if (substr($dir, 0, 1) == '\\') {
		$dir = substr($dir,1);
	}
	if (substr($dir,-1,1) != '/') {
		$dir .= '/';
	}
	return $dir;
}

function fw_file_filter_name($s){
	if ($s == '') {
		return '';
	}
	$s = preg_replace('/[^a-zA-Z0-9_ -]/s', '', $s);
	$s = str_replace(' ', '_', $s);
	$s = str_replace('__', '_', $s);
	$s = strtolower($s);
	
	/*
	$s = preg_replace('/\s/', '_', $s);
	$s = preg_replace('/\n/', '_', $s);
	$s = preg_replace('/\r/', '_', $s);
	$s = preg_replace('/\t/', '_', $s);
	$s = preg_replace('/\v/', '_', $s);
//	$s = preg_replace('/\W+/', '', $s);
	$specialCharacters = array(
							'#' => '_',
							'$' => '_',
							'%' => '_',
							'&' => '_',
							'@' => '_',
							'.' => '_',
							'�' => '_',
							'+' => '_',
							'=' => '_',
							'�' => '_',
							'\\' => '_',
							'/' => '_',
							'!' => '_',
							'^' => '_',
							'*' => '_',
							'(' => '_',
							')' => '_',
							'{' => '_',
							'}' => '_',
							'"' => '_',
							'\'' => '_',
							'<' => '_',
							'>' => '_',
							);

	if ($specialCharacters) {
		while (list($character, $replacement) = each($specialCharacters)) {
			$s = str_replace($character, $replacement, $s);
		}
	}
	*/
	return $s;
}

function fw_file_upload($file_upload, $name, $dir, $extensions){
	if ($file_upload) {
		$dir = fw_clean_dir_path($dir);
		if (!strstr($dir, PATH)) {
			$dir = PATH.$dir;
		}

		$name = $dir.$name;
		//check extension
		$ext = fw_file_extension($file_upload['name']);
		if (!is_array($extensions) && $extensions != '') {
			$extensions = explode(';', $extensions);
		}
		if (!is_array($extensions)) {
			return array('status' => false, 'error' => 'extension_definition');
		}
		if (!in_array($ext,$extensions)) {
			return array('status' => false, 'error' => 'file_extension', 'error_detail' => $ext);
		}

		//create folder if does not exists
		if (!is_dir($dir)) {
			fw_mkdir($dir);//TODO check how it handle subfolders
		}
		//TODO check folder permission if exists is_writeable($dir)
		//move file into destination folder
		if (move_uploaded_file($file_upload['tmp_name'], $name)) {
			if (FILE_CHMOD != '' && file_exists($name)) {
				chmod($name, FILE_CHMOD);
			}
			return array('status' => true);
		} else {
			return array('status' => false, 'error' => 'problem_move');
		}
	} else {
		return array('status' => false, 'error' => 'problem_upload');
	}
}

function fw_mkdir($dir){
	$sep_dir = explode('/', $dir);
	foreach ($sep_dir as $v) {
		$tmp_dir .= '/'.$v;
		if (!is_dir($tmp_dir)) {
			mkdir($tmp_dir, FILE_CHMOD);
		}
	}
}

function fw_file_upload_2($entity, $id, $key = '', $path = ''){
	global $global_config;
	if ($key == '') {
		$key = 'file';
	}
	if (!$path) {
		$path = 'files/data/';
	}
	//set global config for allow extenstion
	$allow_extention = array_keys($global_config['system']['ext_allow']);
	$tmp_dir = $path.date('Y').'/'.date('m');

	//gen name
	$m_name = md5(time().$_SESSION[SESSION_L]);
	$file_tmp_name = $entity.'_'.$id.'_'.$key.'_'.$m_name;//.'.tmp';

	$file_upload_status = fw_file_upload($_FILES[$key], $file_tmp_name, $tmp_dir, $allow_extention);
	$file_upload_status['name'] = $m_name;
	return $file_upload_status;
}
?>